package flex.cc.uac.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.core.annotation.LogAnnotation;
import flex.cc.core.support.BaseController;
import flex.cc.uac.dto.BatchModifyUserStatusDto;
import flex.cc.uac.dto.BindUserRolesDto;
import flex.cc.uac.dto.ModifyUserStatusDto;
import flex.cc.uac.dto.menu.UserMenuDto;
import flex.cc.uac.entity.UacLogEntity;
import flex.cc.uac.entity.UacUserAreaEntity;
import flex.cc.uac.entity.UacUserEntity;
import flex.cc.uac.service.UacUserAreaService;
import flex.cc.uac.service.UacUserService;
import flex.cc.wrapper.WrapMapper;
import flex.cc.wrapper.Wrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户管理主页面.
 */
@RestController
@RequestMapping(value = "/uac/user")
public class UacUserMainController extends BaseController {
    @Resource
    private UacUserService uacUserService;
    @Resource
    private UacUserAreaService uacUserAreaService;

    /**
     * 查询用户列表.
     */
    @PostMapping(value = "/queryListWithPage")
    @ApiOperation(httpMethod = "POST", value = "查询用户列表")
    public Wrapper<IPage<UacUserEntity>> queryUserListWithPage(@ApiParam(name = "user", value = "用户信息")
                                                               @RequestBody UacUserEntity uacUser) {
        logger.info("查询用户列表uacUser={}", uacUser);
        IPage<UacUserEntity> page = uacUserService.queryUserListWithPage(uacUser);
        return WrapMapper.ok(page);
    }

    /**
     * 新增用户
     */
    @LogAnnotation
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增用户")
    public Wrapper<Integer> addUacUser(@ApiParam(name = "user", value = "新增用户Dto")
                                       @RequestBody UacUserEntity user) {
        logger.info("新增用户 user={}", user);
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        user.setLoginName(user.getMobileNo());
        user.setUserCode(user.getMobileNo());
        uacUserService.saveUacUser(user, loginAuthDto);
        return WrapMapper.ok();
    }

    /**
     * 分页查询用户操作日志列表.
     */
    @PostMapping(value = "/queryUserLogListWithPage")
    @ApiOperation(httpMethod = "POST", value = "分页查询用户操作日志列表")
    public Wrapper<IPage<UacLogEntity>> queryUserLogListWithPage(@ApiParam(name = "user", value = "用户信息")
                                                                 @RequestBody UacLogEntity log) {

        logger.info("分页查询用户操作日志列表");
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        IPage<UacLogEntity> page = uacUserService.queryUserLogListWithPage(loginAuthDto.getUserId(),
                log.getPageNum(), log.getPageSize());
        return WrapMapper.ok(page);
    }

    /**
     * 根据Id修改用户状态.
     */
    @PostMapping(value = "/modifyUserStatusById")
    @LogAnnotation
    @ApiOperation(httpMethod = "POST", value = "根据Id修改用户状态")
    public Wrapper<Boolean> modifyUserStatusById(@ApiParam(name = "modifyUserStatusDto", value = "用户禁用/启用Dto")
                                                 @RequestBody ModifyUserStatusDto modifyUserStatusDto) {
        logger.info(" 根据Id修改用户状态 modifyUserStatusDto={}", modifyUserStatusDto);
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        UacUserEntity uacUser = new UacUserEntity();
        uacUser.setId(modifyUserStatusDto.getUserId());
        uacUser.setStatus(modifyUserStatusDto.getStatus());
        boolean result = uacUserService.modifyUserStatusById(uacUser, loginAuthDto);
        return handleResult(result);
    }


    /**
     * 根据Id修改用户状态.
     */
    @PostMapping(value = "/batchModifyUserStatusById")
    @LogAnnotation
    @ApiOperation(httpMethod = "POST", value = "根据Id修改用户状态")
    public Wrapper<Boolean> batchModifyUserStatusById(@ApiParam(name = "batchModifyUserStatusDto", value = "批量修改用户禁用/启用Dto")
                                                 @RequestBody BatchModifyUserStatusDto batchModifyUserStatusDto) {
        logger.info(" 根据Id批量修改用户状态 batchModifyUserStatusDto={}", batchModifyUserStatusDto);
        List<Long> userIds = batchModifyUserStatusDto.getUserIds();
        boolean result = false;
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        for (Long userId:userIds) {
            UacUserEntity uacUser = new UacUserEntity();
            uacUser.setId(userId);
            uacUser.setStatus(batchModifyUserStatusDto.getStatus());
            result = uacUserService.modifyUserStatusById(uacUser, loginAuthDto);
        }
        return handleResult(result);
    }

    /**
     * 通过Id删除用户.
     */
    @LogAnnotation
    @PostMapping(value = "/deleteUserById/{userId}")
    @ApiOperation(httpMethod = "POST", value = "通过Id删除用户")
    public Wrapper<Boolean> deleteUserById(@ApiParam(name = "userId", value = "用户ID") @PathVariable Long userId) {
        logger.info(" 通过Id删除用户 userId={}", userId);

        boolean result = false;
        return handleResult(result);
    }

    /**
     * 获取用户绑定角色页面数据.

    @PostMapping(value = "/getBindRole/{userId}")
    @ApiOperation(httpMethod = "POST", value = "获取用户绑定角色页面数据")
    public Wrapper<UserBindRoleVo> getBindRole(@ApiParam(name = "userId", value = "角色id") @PathVariable Long userId) {
        logger.info("获取用户绑定角色页面数据. userId={}", userId);
        LoginAuthDto loginAuthDto = super.getLoginAuthDto();
        Long currentUserId = loginAuthDto.getUserId();
        if (Objects.equals(userId, currentUserId)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011023);
        }
        UserBindRoleVo bindUserDto = uacUserService.getUserBindRoleDto(userId);
        return WrapMapper.ok(bindUserDto);
    } */

    /**
     * 用户绑定角色.
     */
    @PostMapping(value = "/bindRole")
    @LogAnnotation
    @ApiOperation(httpMethod = "POST", value = "用户绑定角色")
    public Wrapper<Integer> bindUserRoles(@ApiParam(name = "bindUserRolesDto", value = "用户绑定角色Dto") @RequestBody BindUserRolesDto bindUserRolesDto) {
        logger.info("用户绑定角色 bindUserRolesDto={}", bindUserRolesDto);
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        uacUserService.bindUserRoles(bindUserRolesDto, loginAuthDto);
        return WrapMapper.ok();
    }

    /**
     * 查询用户常用功能数据.
     *
     * @return the wrapper
     */
    @PostMapping(value = "/queryUserMenuDtoData")
    @ApiOperation(httpMethod = "POST", value = "查询用户常用功能数据")
    public Wrapper<List<UserMenuDto>> queryUserMenuDtoData() {
        logger.info("查询用户常用功能数据");
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        List<UserMenuDto> userMenuDtoList = uacUserService.queryUserMenuDtoData(loginAuthDto);
        return WrapMapper.ok(userMenuDtoList);
    }

    /**
     * 绑定用户常用菜单.
     *
     * @param bindUserMenusDto the bind user menus dto
     *
     * @return the wrapper

     @LogAnnotation
     @PostMapping(value = "/bindUserMenus")
     @ApiOperation(httpMethod = "POST", value = "绑定用户常用菜单")
     public Wrapper<Integer> bindUserMenus(@ApiParam(name = "bindUserMenusDto", value = "绑定用户常用菜单Dto")
     @RequestBody BindUserMenusDto bindUserMenusDto) {
     logger.info("绑定用户常用菜单");
     List<Long> menuIdList = bindUserMenusDto.getMenuIdList();
     logger.info("menuIdList = {}", menuIdList);

     int result = uacUserService.bindUserMenus(menuIdList, getLoginAuthDto());

     return handleResult(result);

     }*/

    /**
     * 根据用户Id查询用户信息.
     *
     * @param userId the user id
     *
     * @return the uac user by id
     */
    @PostMapping(value = "/getUacUserById/{userId}")
    @ApiOperation(httpMethod = "POST", value = "根据用户Id查询用户信息")
    public Wrapper<UacUserEntity> getUacUserById(@ApiParam(name = "userId", value = "用户ID") @PathVariable Long userId) {
        logger.info("getUacUserById - 根据用户Id查询用户信息. userId={}", userId);
        UacUserEntity uacUser = uacUserService.queryByUserId(userId);
        logger.info("getUacUserById - 根据用户Id查询用户信息. [OK] uacUser={}", uacUser);
        return WrapMapper.ok(uacUser);
    }

    /**
     * 根据用户Id查询用户负责区域信息.
     *
     * @param userId the user id
     *
     * @return the uac user area by id
     */
    @PostMapping(value = "/queryUserAreaByUserId/{userId}")
    @ApiOperation(httpMethod = "POST", value = "根据用户Id查询用户信息")
    public Wrapper<UacUserAreaEntity> queryUserAreaByUserId(@ApiParam(name = "userId", value = "用户ID") @PathVariable Long userId) {
        logger.info("queryUserAreaByUserId - 根据用户Id查询用户负责区域信息. userId={}", userId);
        UacUserAreaEntity uacUserArea = uacUserAreaService.queryUserAreaByUserId(userId);
        logger.info("queryUserAreaByUserId - 根据用户Id查询用户负责区域信息. [OK] uacUserArea={}", uacUserArea);
        return WrapMapper.ok(uacUserArea);
    }


    /**
     * 根据用户Id重置密码.
     *
     */
    @LogAnnotation
    @PostMapping(value = "/resetLoginPwd/{userId}")
    @ApiOperation(httpMethod = "POST", value = "根据用户Id重置密码")
    public Wrapper<UacUserEntity> resetLoginPwd(@ApiParam(name = "userId", value = "用户ID") @PathVariable Long userId) {
        logger.info("resetLoginPwd - 根据用户Id重置密码. userId={}", userId);
        uacUserService.resetLoginPwd(userId, getLoginAuthDto());
        return WrapMapper.ok();
    }


    /**
     * 根据用户Id批量重置密码.
     *
     */
    @LogAnnotation
    @PostMapping(value = "/batchResetLoginPwd")
    @ApiOperation(httpMethod = "POST", value = "根据用户Id重置密码")
    public Wrapper<UacUserEntity> resetLoginPwd(@ApiParam(name = "idList", value = "角色Id") @RequestBody List<Long> idList) {
        logger.info("batchResetLoginPwd - 根据用户Id批量重置密码. userIds={}", idList);
        uacUserService.batchResetLoginPwd(idList, getLoginAuthDto());
        return WrapMapper.ok();
    }


    /**
     * 修改密码.
     *
     */
    @LogAnnotation
    @GetMapping(value = "/changeLoginPwd")
    @ApiOperation(httpMethod = "get", value = "根据机构获取所有父级")
    public Wrapper changeLoginPwd(@RequestParam(required = true) String oldPassWord, String newPassWord) {
    	logger.info("修改用户密码");
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        if(loginAuthDto != null && loginAuthDto.getUserId() != null) {
        	if(newPassWord == null || "".equals(newPassWord)) {
        		return WrapMapper.error("密码修改失败，请输入新密码");
        	} else {
        		UacUserEntity uacUser = uacUserService.queryByUserId(loginAuthDto.getUserId());
            	if(uacUser == null) {
            		return WrapMapper.error("密码修改失败，用户不存在");
            	} else {
            		if(oldPassWord != null && oldPassWord.equals(uacUser.getLoginPwd())) {
            			uacUser.setLoginPwd(newPassWord);
            			short isChangedPwd = 1;
            			uacUser.setIsChangedPwd(isChangedPwd);
            			uacUser.setUpdateInfo(loginAuthDto);
                		boolean updateResult = uacUserService.updateUser(uacUser);
                		if(updateResult) {
                            return WrapMapper.ok();
                		} else {
                            return WrapMapper.error("密码修改失败，请重试");
                		}
            		} else {
            			return WrapMapper.error("密码修改失败，原密码错误");
            		}
            	}
        	}
        }else {
        	 return WrapMapper.error("登录已过期，请重新登录");
        }
    }
}
